//
//  PhotoBrowserViewController.swift
//  Weibo
//
//  Created by Heaven on 15/7/5.
//  Copyright © 2015年 Heaven. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class PhotoBrowserViewController: UIViewController {
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func save() {
        
        // 0. 拿到当前的cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PhotoViewerCell
        
        // 1. 拿到图像
        let image = cell.imageView.image!
        
        // 2. 保存图像 - 回调方法的参数格式是固定的
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    func image(image :UIImage, didFinishSavingWithError error:NSError?, contextInfo :AnyObject) {
        
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存出错")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print(imageURLs)
    }
    
    // 将要出现，视图 OK，collectionView 不 OK
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        print("\(__FUNCTION__) \(view.frame) \(collectionView.frame)")
    }
    
    // 将要布局，视图 OK，collectionView 不 OK
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        print("\(__FUNCTION__) \(view.frame) \(collectionView.frame)")
    }
    
    // 完成子视图，视图 OK，collectionView OK
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        print("\(__FUNCTION__) \(view.frame) \(collectionView.frame)")
        
        prepareLayout()
        
        // 跳转到用户选定的页面
        let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    private func prepareLayout() {
        // 设定所有的 item 的尺寸
        layout.itemSize = collectionView.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        collectionView.ff_Fill(view)
        saveButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        closeButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(PhotoViewerCell.self, forCellWithReuseIdentifier: YTPhotoBrowserCellReuseIdentifier)
    }
    
    init(urls: [NSURL], index: Int) {
        // 先初始化本类的属性
        imageURLs = urls
        currentIndex = index
        
        // `再`调用系统提供的 `父类` 构造函数
        super.init(nibName: nil, bundle: nil)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 图像的数组
    private var imageURLs: [NSURL]
    /// 用户选中的照片索引
    private var currentIndex: Int
    
    // MARK: － 控件懒加载
    lazy private var layout = UICollectionViewFlowLayout()
    lazy private var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    lazy private var saveButton: UIButton = UIButton(title: "保存", fontSize: 14)
    lazy private var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14)
}

private let YTPhotoBrowserCellReuseIdentifier = "YTPhotoBrowserCellReuseIdentifier"

extension PhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate, PhotoViewerCellDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YTPhotoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PhotoViewerCell
        
        cell.backgroundColor = UIColor.randomColor()
        cell.imageURL = imageURLs[indexPath.item]
        
        cell.photoDelegate = self
        
        return cell
    }
    
    // 全屏状态下，此方法不会被触发
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print(__FUNCTION__)
    }
    
    // 点击关闭
    func photoViewerCellDidTapImage() {
        // 关闭界面
        close()
    }
}